package Example;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author:  LiuTao
 * Version: 1.0
 * Date:    2023-12-07  08:45
 */

public class Main2 {
   private static volatile int count = 0;

   private static Object locker = new Object();

   public static void main(String[] args) {

      Thread A = new Thread(() -> {
         for(int i = 0; i < 10; i++) {
            synchronized (locker) {
               while(count % 3 != 0) {
                  try {
                     locker.wait();
                  } catch (InterruptedException e) {
                     throw new RuntimeException(e);
                  }
               }
               System.out.print(Thread.currentThread().getName());
               count++;
               locker.notifyAll();
            }
         }
      },"A");

      Thread B = new Thread(() -> {
         for(int i = 0; i < 10; i++) {
            synchronized(locker) {
               while (count % 3 != 1) {
                  try {
                     locker.wait();
                  } catch (InterruptedException e) {
                     throw new RuntimeException(e);
                  }
               }
               System.out.print(Thread.currentThread().getName());
               count++;
               locker.notifyAll();
            }
         }
      },"B");

      Thread C = new Thread(() -> {
         for(int i = 0; i < 10; i++) {
            synchronized(locker) {
               while(count % 3 != 2) {
                  try {
                     locker.wait();
                  } catch (InterruptedException e) {
                     throw new RuntimeException(e);
                  }
               }
               System.out.println(Thread.currentThread().getName());
               count++;
               locker.notifyAll();
            }
         }
      },"C");

      A.start();
      B.start();
      C.start();
   }
}